package com.cube.share.handler.config;

import com.cube.share.base.templates.IEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author poker.li
 * @date 2021/7/30 11:52
 * <p>
 * 自定义枚举类处理器
 */
public class IEnumTypeHandler<C extends Serializable, V extends Serializable, E extends Enum<?> & IEnum<C, V>> extends BaseTypeHandler<IEnum<C, V>> {

    private final Class<E> type;

    public IEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Enum type must be not null!");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, IEnum parameter, JdbcType jdbcType) throws SQLException {
        ps.setObject(i, parameter.getCode());
    }

    @Override
    public IEnum<C, V> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        @SuppressWarnings("unchecked") C code = (C) rs.getObject(columnName);
        return rs.wasNull() ? null : IEnum.formCode(type, code);
    }

    @Override
    public IEnum<C, V> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return rs.wasNull() ? null : IEnum.formCode(type, columnIndex);
    }

    @Override
    public IEnum<C, V> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        @SuppressWarnings("unchecked") C code = (C) cs.getObject(columnIndex);
        return cs.wasNull() ? null : IEnum.formCode(type, code);
    }
}
